﻿//************************************************************************************************************
// CoNatural.Data.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using CoNatural.Data.Helpers;
using CoNatural.Binders;

namespace CoNatural.Data.Binders {
	/// <summary>
	/// Binder delegate factory for ICommand
	/// </summary>
	public class ModelBinderDelegateFactory : PropertyBinderDelegateFactory {
		protected override PropertyMapping GetMapping(PropertyInfo sourceProperty, PropertyInfo targetProperty, string sourcePath, string targetPath, int level) {
			var mapping = base.GetMapping(sourceProperty, targetProperty, sourcePath, targetPath, level);
			if (mapping != null) {
				// ignore output parameters when binding to commands
				if(targetProperty.DeclaringType.GetInterface(typeof(ICommand).ToString()) != null) {
					object[] attributes = targetProperty.GetCustomAttributes(typeof(ParameterAttribute), false);
					if(attributes.Length > 0) {
						var attr = attributes[0] as ParameterAttribute;
						if(attr.Direction == ParameterDirection.Output)
							return null;
					}
				}
				// ignore input parameters when binding from commands
				if(sourceProperty.DeclaringType.GetInterface(typeof(ICommand).ToString()) != null) {
					object[] attributes = sourceProperty.GetCustomAttributes(typeof(ParameterAttribute), false);
					if(attributes.Length > 0) {
						var attr = attributes[0] as ParameterAttribute;
						if(attr.Direction == ParameterDirection.Input)
							return null;
					}
					else
						return null; // input by default
				}
			}
			return mapping;
		}
	}
}
